package cn.com.io.day20151210;

import java.io.FileReader;
import java.io.IOException;
import java.io.PushbackReader;

/**
 * Created by Administrator on 2015/12/10.
 */
public class PushbackTest {
    public static void main(String[] args) {
        PushbackReader pushbackReader = null;
        try {
            pushbackReader = new PushbackReader(new FileReader(System.getProperty("user.dir")+"\\src\\cn\\com\\io\\day20151210\\PushbackTest.java"), 64);//创建一个PushbackReader对象，指定推回缓冲区的长度为64
            char[] buf = new char[32];
            String lastContent = "";//用以保存上次读取的字符串内容
            int hasRead = 0;
            while ((hasRead = pushbackReader.read(buf)) > 0) {
                //循环读取文件内容,并将读取的内容转换成字符串
                String content = new String(buf, 0, hasRead);
                int targetIndex = 0;
                if ((targetIndex = (lastContent + content).indexOf("new PushbackReader")) > 0) {
                    //将本次读取到的内容和上次读取到的内容一起推回到缓冲区中
                    pushbackReader.unread((lastContent + content).toCharArray());
                    //再次读取指定长度的内容（就是目标字符串之前的内容）
                    pushbackReader.read(buf, 0, targetIndex);
                    //打印读取的内容
                    System.out.println(new String(buf, 0, targetIndex));
                    System.exit(0);
                } else {
                    //打印上次读取的内容
                    System.out.println(lastContent);
                    //将本次读取的内容设为上次读取的内容
                    lastContent = content;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(pushbackReader != null ){
                try {
                    pushbackReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
